package com.zhq.blog.manage.domain.fronted.controller;

import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.zhq.blog.core.domain.Context;
import com.zhq.blog.core.domain.request.RequestContext;
import com.zhq.blog.core.domain.user.User;
import com.zhq.blog.manage.domain.fronted.controller.support.UserInterceptor;

/**
 * @title:BaseController.java
 * @package com.zhq.blog.manage.domain.fronted.controller
 * @author 张恒强
 * @date 2015年1月5日 上午10:53:06
 * @version V1.0
 */
@Transactional
public abstract class BaseController{
	
	public Log logger = LogFactory.getLog(this.getClass());
	
	public static final String CURRENT_USER_OBJECT_ATTRIBUTE = "user";
    
	
	User currentUser;
	boolean isGuest;
	RequestContext request;
	
	@Autowired
	Context context;
	
	void DEBUG(Object message){
		if(logger.isDebugEnabled()) logger.debug(message);
	}
	void DEBUG(Object message,Throwable t){
		if(logger.isDebugEnabled()) logger.debug(message, t);
	}	
	
	void INFO(Object message){
		logger.info(message);
	}
	void ERROR(Object message){
		logger.error(message);
	}	

	public User getCurrentUser() {
		return currentUser;
	}
	public void setCurrentUser(User currentUser) {
		this.currentUser = currentUser;
	}
	
	@Autowired
	private SessionUser session;

	public SessionUser getSession() {
		return session;
	}
	public void setSession(SessionUser session) {
		this.session = session;
	}
	
	public void init(){
		
	}	
	MallModelView buildModelView(HttpServletRequest request){
		return buildModelView(null,request);	
	}
	
	MallModelView buildModelView(String viewName,HttpServletRequest request){
		MallModelView model = new MallModelView();
		model.setViewName(viewName);
		if(request.getSession().getAttribute(UserInterceptor.SESSION_ID_FLAG)==null){
			model.addObject(CURRENT_USER_OBJECT_ATTRIBUTE,null);
		}else{
			///更新user
			User user = context.getUserRepository().findOne(((User)request.getSession().getAttribute(UserInterceptor.SESSION_ID_FLAG)).getId());
			request.getSession().setAttribute(UserInterceptor.SESSION_ID_FLAG, user);
			model.add(CURRENT_USER_OBJECT_ATTRIBUTE,user);
		}
		String uri = request.getRequestURI();
		if (uri.contains(";")) {
			uri = uri.split(";")[0];
		}
		if (uri.matches("^/fgame/\\d+/\\w+$")) {
			model.add("game", context.getGameRepository().findOne(Long.parseLong(uri.split("/")[2])));
			model.add("games", context.getGameRepository().findAll());
		}
		
		return model;	
	}
}
